import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Button, Card, Col, Form, Icon, Input, message, Row, Table} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../PrivateFile.less';
import DirLine from "../sub/DirLine";
import router from 'umi/router';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ftpModel, loading}) => ({
  ftpModel,
  loading: loading.models.ftpModel,
}))
@Form.create()
class FtpList extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    record: {},
    currentDirs: [{code: 'index', dirName: '我的文件库'},{code: 'ftp_list', dirName: '外接文件'},],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'name',
      render: (text, row) => {
        return <Fragment>
          <Icon type="folder" theme="filled" style={{color: '#e87e04'}}/>&nbsp;
          <a onClick={() => this.querySubDir(row)}>{text}</a>
        </Fragment>
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',

      render:
        val => val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : null,
    },

  ];

  componentDidMount() {

    const {dispatch} = this.props;
    dispatch({
      type: 'ftpModel/queryOutFtpList',
    });

  }



  //选中了目录
  onDirSelect = item => {
    switch (item.code) {
      case 'index':
        router.push('/filecenter/home-file');
        break;
      case 'ftp_list':
        break;
      default:
        break;
    }
  }


  //显示文件夹下级内容
  querySubDir = (row) => {
    router.push('/filecenter/out-file/outfiles/' + row.id + '/' + row.name);
  };

  /***预览文件**/
  previewItem = id => {
    //获取编辑地址
    const {dispatch} = this.props;
    dispatch({
      type: 'ftpModel/getPreviewLinkPath',
      payload: {
        // fileId: record.id,
        fileId: 13,
      },
      callback: (res) => {
        if (res.result == "ok") {
          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          message.error(res.msg);
        }
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
        parentId: 0,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'ftpModel/queryList',
        payload: values,

      });
    });
  };
  /********移动文件到其他地方*******/
  handleMove = (newParentId, record) => {
    const {dispatch,} = this.props;
    dispatch({
      type: 'ftpModel/moveFile',
      payload: {
        ftpId: record.ftpId,
        parentId: newParentId || 0,
        fileDir: record.fileDir + "\\" + record.dirName,
        fileName: record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {
          message.success(res.msg);
          this.handleMoveModalVisible();
          this.querySubDirOrFileList(record);
        } else {
          message.error(res.msg)
        }
      },
    })
    ;
  };
  /**
   * 移动文件弹出框
   * @param flag
   * @param record
   */
  handleMoveModalVisible = (flag, record) => {
    this.setState({
      moveModalVisible: !!flag,
      record: record || {},
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('dirName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="创建人">
              {getFieldDecorator('creater')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {

    const {
      ftpModel: {data,},
      loading,
    } = this.props;
    const {selectedRows, moveModalVisible, record, currentDirs} = this.state;

    //移动文件
    const moveMethods = {
      handleMove: this.handleMove,
      handleModalVisible: this.handleMoveModalVisible,
    };

    return (
      <PageHeaderWrapper title="外接文件">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.filePath}>
              <DirLine dirs={currentDirs} onDirSelect={this.onDirSelect}/>
            </div>
            <Table className={styles.tdPadding} columns={this.columns} dataSource={data.dataList}/>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default FtpList;
